#coding=utf-8
from django.contrib.admin.helpers import AdminReadonlyField
from django.db.models import ManyToManyField
from django.forms import ModelForm, ModelChoiceField, ModelMultipleChoiceField
from PublicTool.CzqWidget import ShowWidget


__author__ = 'czq'
class ShowModelForm(ModelForm):
    def __init__(self, hidden_fields=[], readonly_fields=[],show_all=True,*args, **kwargs):
        super(ShowModelForm, self).__init__(*args, **kwargs)
        for field in hidden_fields:
            del self.fields[field]
        if self.instance.id:
            if show_all:
              #设置浏览器端的只读属性
              for field in self.fields:
                  read = AdminReadonlyField(self, field, is_first=(False),model_admin=self)
                  html=read.contents()
                  if isinstance(self.fields[field],ModelMultipleChoiceField):
                      self.fields[field].help_text=u''
                      html=html.replace(',','<br/>')
                  self.fields[field].widget=ShowWidget(html)
            else:
              #设置浏览器端的只读属性
              for field in readonly_fields:
                read = AdminReadonlyField(self, field, is_first=(False),model_admin=self)
                self.fields[field].widget=ShowWidget(read.contents())
                #setattr(self, 'clean_%s' % field, lambda : getattr(self.instance, field))
            #将需要隐藏的字段逐个从self.fields中删除, 这样这些字段就不会呈现给用户了.


